package me.uniauto.service;


import me.uniauto.util.BusinessDataCode;
import me.uniauto.util.CommResp;
import me.uniauto.util.MyStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import tk.mybatis.mapper.common.Mapper;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * service 基类。extends AbstractEvent 被观察者
 */
public abstract class BaseService<T> implements IService<T> {

    @Value("${baseUrl}")
    private static String BASE_URL;

    @Autowired
    protected Mapper<T> mapper;


    public BaseService() {
    }

    /** php时间戳 */
    public int php_time() {
        return Integer.valueOf((System.currentTimeMillis() + "").substring(0,
                10));
    }
    /** 时间 */
    public String timeUid() {
        Date now = new Date();
        SimpleDateFormat timeUidSdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return timeUidSdf.format(now);
    }


    private IAdapter adapter;
    @Override
    public void setAdapter(IAdapter adapter) {
        this.adapter=adapter;
    }

    @Override
    public IAdapter getAdapter() {
        if (adapter==null){
            adapter=createAdapter();
        }
        return adapter;
    }
    abstract protected IAdapter createAdapter();

    /**
     * 处理图片路径
     *
     * @param img
     * @return
     */
    public static String addHttp2UriStart(String img) {
        if (null == img || "null" == img || img.contains("http://") || img.contains("https://") || MyStringUtil.isBlank(img) || "undefined".equals(img)) {
            return img;
        } else {
            return BASE_URL + File.separator + img;
        }
    }


    /**
     * 返回不带参数的成功
     */
    protected CommResp success(){
        CommResp resp = new CommResp(BusinessDataCode.SUCCESS);
        return resp;
    }

    /**
     * 返回带参数的成功
     */
    protected CommResp success(Object data){
        CommResp resp = new CommResp(BusinessDataCode.SUCCESS);
        resp.setData(data);
        return resp;
    }

    /**
     * 根据条件查询返回list集合
     */
    @Override
    public List selectByExampleSelective( Object example) {
        return mapper.selectByExample(example);
    }

    @Override
    public int insert(T entity) {
        return mapper.insert(entity);
    }

    @Override
    public int updateByExampleSelective(T entity, Object example) {
        return mapper.updateByExampleSelective(entity,example);
    }

    @Override
    public T selectOne(T entity) {
        return mapper.selectOne(entity);
    }
}